package tech.yqyl.solo.processor;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.text.StrFormatter;
import tech.yqyl.StringUtil;
import tech.yqyl.YamlUtils;
import tech.yqyl.config.ImageBedConfig;
import tech.yqyl.git.GitRepository;
import tech.yqyl.halo.HaloMarkdownBoot;
import tech.yqyl.solo.BlogInfo;
import tech.yqyl.solo.BlogProcessor;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @className: Img2GiteeProcessor
 * @description:
 * @author: caoyangjie
 * @date: 2024/9/6
 **/
public class Img2GiteeProcessor extends AbstractProcessor implements BlogProcessor {
    @Override
    public boolean filter() {
        return true;
    }

    @Override
    public void process(BlogInfo blog) {
        List<String> images = getAllImages(blog.getArticle().getArticleContent());
        Set<String> needDown = new HashSet<>();
        // 没有需要下载的图片则,直接返回
        if (CollectionUtil.isEmpty(images)) {
            return;
        }
        needDown.addAll(images.parallelStream().filter(url->!url.contains("gitbook.luckycxy.com")).collect(Collectors.toList()));
        // 没有需要下载的图片则,直接返回
        if( CollectionUtil.isEmpty(needDown) ) {
            return;
        }
        // 下载图片并上传到图床
        GitRepository.init().store(blog.getArticle().getFirstTag(), needDown, blog);
        ImageBedConfig imgBed = YamlUtils.getConfig().getImgBed();
        String imgProcessorContent = blog.getArticle().getArticleContent();
        for( String url : needDown ){
            String lastPath = StringUtil.hashString(blog.getArticle().getFirstTag())
                    .concat(File.separator)
                    .concat(StringUtil.hashString(url))
                    .concat(".")
                    .concat(GitRepository.getImageType(url));
            String replaceUrl = StrFormatter.format("{}/{}/{}", imgBed.getDomain(), imgBed.getBasePath(), lastPath);
            imgProcessorContent = imgProcessorContent.replaceAll(url, replaceUrl);
        }
        // 将图片处理后的结果放回去
        blog.getArticle().setArticleContent(imgProcessorContent);
    }

    private List<String> getAllImages(String articleContent) {
        try {
            return StringUtil.extractImageUrls(articleContent);
        } catch (IOException e) {
            System.err.println(StrFormatter.format("抽取图片资源失败:{}", e.getMessage()));
        }
        return new ArrayList<>();
    }


}
